<?php

if (!isset($_REQUEST['subsite']) || !in_array($_REQUEST['subsite'], array('shop', 'wap', 'backend','dunch'))) { //mod by  allen.qiang  2015年1月21日 下午茶FUN-AC-0028  (加入“dunch”)
    if ($_SERVER['SCRIPT_NAME'] == '/index.php') {
        define('G_SHOP_SUBSITE', 'shop');
    } else {
        define('G_SHOP_SUBSITE', 'backend');
    }
} else {
    define('G_SHOP_SUBSITE', $_REQUEST['subsite']);
    unset($_REQUEST['subsite']);
}

require ('module/func/quanli.func.php');
quanli_require( 'core/app.config.php' );
quanli_require( 'core/entity.php' );
quanli_require( 'core/DBCAFactory.php' );
quanli_require( 'core/memoryCache.php' );
quanli_require( 'core/smartyFactory.php');
quanli_require( 'core/eaiFactory.php' );
quanli_require( 'core/cacheDataLogic.php' );

class shop {

    private $DBCA_Instance = null;
    private $smarty_Instance = null;
    public  $memoryCache_Instance = null;
    private $vars = null;
    private $subsite = null;

    function __construct( $subsite ) {
        $this->memoryCache_Instance = new memoryCache ();
        $this->subsite = $subsite;
    }

    public function __get($name) {

        switch ($name) {

            case 'DBCA' :
                if (! isset ( $this->DBCA_Instance ))
                    $this->DBCA_Instance = DBCAFactory::web_create ();
                return $this->DBCA_Instance;
                break;

            case 'mid_DBCA':
                return DBCAFactory::mid_create ();
                break;

            case 'smarty' :
                if (! isset ( $this->smarty_Instance ))
                    $this->smarty_Instance = smartyFactory::create ();
                return $this->smarty_Instance;
                break;

            case 'currentPCustID' : //前台会员号
                if ($login_session = $this->sessionCache_get ( 'LOGINSESSION' )) {
                    if (isset ( $login_session ['pcustID'] ))
                        return $login_session ['pcustID'];
                }
                return null;
                break;

            case 'currentCustomerID' : //前台会员名
                if ($login_session = $this->sessionCache_get ( 'LOGINSESSION' )) {
                    if (isset ( $login_session ['custID'] ))
                        return $login_session ['custID'];
                }
                return null;
                break;

            case 'isGuest': //前台登录会员类型 1、访客 0、会员
            	if ($login_session = $this->sessionCache_get ( 'LOGINSESSION' )) {
                    if (isset ( $login_session ['guest'] ))
                        return $login_session ['guest'];
                }
                return 1;
                break;

            case 'isCustomerLogon' : //判断前台会员是否登录
                return $this->sessionCache_get ( 'LOGINSESSION' ) != false;
                break;

            case 'currentUserID' : //后台用户名
                if ($login_session = $this->sessionCache_get ( 'PS_LOGIN_SESSION' )) {
                    if (isset ( $login_session ['USER_ID'] ))
                        return $login_session ['USER_ID'];
                }
                return null;
                break;

            case 'currentUserName' : //后台用户姓名
                if ($login_session = $this->sessionCache_get ( 'PS_LOGIN_SESSION' )) {
                    if (isset ( $login_session ['USER_NAME'] ))
                        return $login_session ['USER_NAME'];
                }
                return null;
                break;

            case 'isUserLogon' : //判断后台用户是否登录
                return $this->sessionCache_get ( 'PS_LOGIN_SESSION' ) != false;
                break;

            case 'sys_date' :
                return date ( G_DEFAULT_DATE_FORMAT );
                break;

            case 'sys_datetime' :
                return date ( G_DEFAULT_DATETIME_FORMAT );
                break;

            default :
                if (isset ( $this->vars [$name] ))
                    return $this->vars [$name];
                if (defined ( $name ))
                    return constant ( $name );
                return null;
                break;

        }

    }

    public function eai( $eai_name ) {
        return eaiFactory::web_eai( $eai_name );
    }

    /**
     * 转跳到前台登录页（web、wap）
     */
    public function goto_login() {

        $request_url = '';
        if (strcasecmp ( $_SERVER ['REQUEST_URI'], "/$this->subsite/login.html" ) != 0) {
            $request_url = '?requrl=' . urlencode ( $_SERVER ['REQUEST_URI'] );
        }
        header ( "location: login.html" . $request_url );
        die ();
    }

    /**
     * 转跳到错误页面
     * @param string $error_msg 错误信息，默认为空
     */
    public function display_error_page( $error_msg = '') {
        if (in_array($this->subsite, array('shop', 'wap'))) {
            header ( 'location: /' . $this->subsite . '/404.html' );
        } else {
            if ($error_msg != '') {
                $this->sessionCache_set ( 'quanliadmin_ERROR_MSG', $error_msg, 3600 );
            }
            header ( 'location: /quanliadmin/error.php' );
        }
        die ();
    }

    /**
     * 保存session数据
     * @param string $key 键值
     * @param mixed $value 值
     * @param number $timeout 时效
     * @param bool $global 判断键值前是否加session_id  true：不加 false：加
     * @return bool
     */
    public function sessionCache_set($key, $value, $timeout, $global = false) {
        if ($global)
            $tmp_key = $key;
        else
            $tmp_key = session_id () . $key;
        return $this->memoryCache_Instance->set ( $tmp_key, $value, $timeout );
    }

    /**
     * 获取保存session里的数据
     * @param string $key 键值
     * @param bool $global 判断键值前是否加session_id  true：不加 false：加
     * @return mixed
     */
    public function sessionCache_get($key, $global = false) {
        if ($global)
            $tmp_key = $key;
        else
            $tmp_key = session_id () . $key;
        return $this->memoryCache_Instance->get ( $tmp_key );
    }

    /**
     * 删除session里的数据
     * @param string $key 键值
     * @param bool $global 判断键值前是否加session_id  true：不加 false：加
     */
    public function sessionCache_remove($key, $global = false) {
        if ($global)
            $tmp_key = $key;
        else
            $tmp_key = session_id () . $key;
        return $this->memoryCache_Instance->remove ( $tmp_key );
    }

    /**
     * 返回匹配的键值.
     * @param string $pattern 键值
     * @param bool $global 判断键值前是否加session_id  true：不加 false：加
     * @return array of string
     */
    public function sessionCache_keys($pattern, $global = false) {
        if ($global)
            $tmp_pattern = $pattern;
        else
            $tmp_pattern = session_id () . $pattern;
        return $this->memoryCache_Instance->keys ( $tmp_pattern );
    }

    /**
     * 前台显示smarty模板，同时生成html静态缓存（前台）
     * @param string $act 控制器，值等于"do_flush"时生成html静态缓存
     * @param string $tpl 模板文件名称
     * @param string $html_file 缓存文件绝对地址
     */
    public function smarty_display($act, $tpl, $html_file) {
        ob_start ();
        $this->smarty->display ( $tpl );
        if ($act == 'do_flush') {
            $htmlcache_dir = dirname ( $html_file );
            if (!file_exists($htmlcache_dir))
                mkdir ( $htmlcache_dir, 0777, true );
            file_put_contents ( $html_file, ob_get_contents () );
        }
        ob_end_flush ();
    }

    /**
     * 检查文件缓存，判断是否可以继续执行（前台）
     * @param $html_file 缓存文件路径
     * @param $cachetime 缓存生存时间 默认1小时 edit by allen.qiang 2015-05-25
     * @return string
     */
    function htmlcache_phpcall( $html_file, $cachetime = 3600 ) {

        if (!isset($html_file) || empty($html_file)) {
            die ( 'Access denied.' );
        }

        //如启用了页面缓存，判断页面缓存是否存在或超时，重新生成缓存文件，add by allen.qiang 2015-05-25 Start
        if (T_HTML_CACHE_ENABLED && ((is_file($html_file) && (time()-filemtime($html_file)) >= $cachetime) || !file_exists($html_file))) {
            return 'do_flush';
        }
        //如启用了页面缓存，判断页面缓存是否存在或超时，重新生成缓存文件，add by allen.qiang 2015-05-25 Start

        if (!G_HTML_CACHE_ENABLED) { //缓存没有启用，允许php调用
            return 'do_display';
        }

        if (!file_exists($html_file)) { //启用了缓存，缓存文件不存在，允许php调用
            return 'do_flush';
        }

        if (!isset ( $_REQUEST ['act'] )) { //以下情况，缓存文件已经存在，禁止php调用
            die ( 'Access denied.' );
        }

        $act = decryptD ( $_REQUEST ['act'] );
        $act_params = explode ( '_', $act );

        if (! (is_array ( $act_params ) && count ( $act_params ) == 3)) {
            die ( 'Access denied.' .$act);
        }
        $req_act = $act_params [1];
        switch ($req_act) {
            case 'callpreView' :
                return 'do_display';
                break;
            case 'callpUblish' :
                return 'do_flush';
                break;
            default :
                die ( 'Access denied.' );
                break;
        }
        die ( 'Access denied.' );
    }

    /**
     * 保存cookie数据
     * @param string $name cookie名
     * @param string $value cookie值
     * @param int $timeout cookie时效
     * @return bool
     */
    public function set_cookie_info($name, $value, $timeout=0) {
        if (!isset($name) || empty($name)) {
            return false;
        }
        if (!isset($value)) {
            return false;
        }
        if ($timeout == 0) {
            return setcookie($name, urlencode($value), 0, '/', G_COOKIE_DOMAIN);
        } else {
            return setcookie($name, urlencode($value), time() + $timeout, '/', G_COOKIE_DOMAIN);
        }

    }

    /**
     * 获取cookie数据
     * @param string $name cookie名
     * @return null|string
     */
    public function get_cookie_info($name) {
        if (!isset($name) || empty($name)) {
            return null;
        }
        if (isset($_COOKIE[$name])) {
            return urldecode($_COOKIE[$name]);
        } else {
            return null;
        }
    }

    /**
     * 根据权限ID判断用户是否有权限（后台）
     * @param int $permission_id 权限ID
     * @param $permission_id
     * @return bool
     */
    public function has_permission($permission_id) {
        if (!isset($permission_id) || !is_numeric($permission_id) || $permission_id <= 0) {
            return 0;
        }
        if ($login_session = $this->sessionCache_get ( 'PS_LOGIN_SESSION' )) {
            if (isset ( $login_session ['USER_PERMISSIONS'] )) {
                if (array_key_exists ( $permission_id, $login_session ['USER_PERMISSIONS'] )) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
        return 0;
    }

    /**
     * 根据访问的url检查是否有权限（后台）
     * @param string $aclURI 访问链接
     * @return bool
     */
    public function acl_check($aclURI) {
        if (! $PERMISSIONED_URI = $this->sessionCache_get ( 'PS_PERMISSIONEDURI', true )) {
            $result_puri = $this->mid_DBCA->stmt_query('SELECT permissionID,permissionRequest FROM user_permission');
            foreach ( $result_puri as $p_uri ) {
                $PERMISSIONED_URI [md5 ( $p_uri->permissionRequest )] = $p_uri->permissionID;
            }
            $this->sessionCache_set ( 'PS_PERMISSIONEDURI', $PERMISSIONED_URI, 0, true );
        }
        $aclURI_key = md5 ( $aclURI );
        if (key_exists ( $aclURI_key, $PERMISSIONED_URI )) {
            return $this->has_permission ( $PERMISSIONED_URI [$aclURI_key] );
        } else {
            return true;
        }
    }

    public function init() {
        session_start ();
        if (in_array($this->subsite, array('shop', 'wap'))) {
            //检查访问的页面是否需要登录
            $needAuthorizedScripts = '';
            include(G_CONFIG_ROOT . 'scriptConDef.php');
            if (array_key_exists ( $_SERVER ['SCRIPT_NAME'], $needAuthorizedScripts )) {
                if (! $this->isCustomerLogon) {
                    $this->goto_login ();
                } elseif ( $this->isGuest == 0 && (! isset ( $_COOKIE ['WANSONSHOP_IDENTIFIER'] ) || $this->get_cookie_info('WANSONSHOP_IDENTIFIER') != $this->currentCustomerID)) {
                    error_log($this->isGuest);
                    $this->goto_login ();
                }
            }
        }
        $this->vars ['remoteIP'] = isset ( $_SERVER ['HTTP_X_REAL_IP'] ) ? $_SERVER ['HTTP_X_REAL_IP'] : $_SERVER ['REMOTE_ADDR'];
        $this->vars ['remotePort'] = $_SERVER ['REMOTE_PORT'];
    }

    /**
     * add by allen.qiang 20170118
     * 读取缓存数据，如缓存没有，则更新缓存
     * @param string $name
     * @return null|string
     */
    public function getCache($nameKey,$cityId =0) {
        //读取缓存内容
        $cacheData = $this->memoryCache_Instance->get ( $nameKey );
        //判断缓存内容是否存在
        if(!isset($cacheData) || is_null($cacheData)){
            error_log('cache info: [' . $nameKey . '] 数据未命中，重新读取。');
            //todo:更新缓存，新建业务类，专门处理缓存数据读取，存储逻辑
            $cacheDataLogic = new cacheDataLogic();
            $cacheDataLogic->cityId = $cityId;                                      //设置城市属性
            $cacheData = $cacheDataLogic->reloadCacheData($nameKey);
        }
        //返回数据
        return $cacheData;
     }

    /**
     * add by allen.qiang 20170118
     * 刷新缓存数据
     * @param string $name
     * @return null|string
     */
    public function setCache($nameKey) {
        error_log('cache info: [' . $nameKey . '] 数据重新读入缓存。');
        $cacheDataLogic = new cacheDataLogic();
        $cacheDataLogic->reloadCacheData($nameKey);
    }


}

$G_SHOP = new shop ( G_SHOP_SUBSITE );
$G_SHOP->init ();
$G_PGLOB = &$G_SHOP;
$G_WAP = &$G_SHOP;

function GS(){ global $G_SHOP; return $G_SHOP; }

/**
 * 加载公共smarty文件
 */
quanli_require('module/smarty/' . G_SHOP_SUBSITE . '.smarty.php');
if (G_SHOP_SUBSITE == 'backend') {
    quanli_require('quanliadmin/comm/smarty_fun.php');
}